package com.lill.support.aspect;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.lill.support.annotation.ParamDecode;

@Component
public class HandlerParamDecodeResolver implements HandlerMethodArgumentResolver {

	@Value("paramKey")
	private String key;
	
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(ParamDecode.class);
	}

	public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer mavContainer, NativeWebRequest webRequest,WebDataBinderFactory binderFactory) throws Exception {
		ParamDecode decode=parameter.getParameterAnnotation(ParamDecode.class);
		String paramName=decode.name();
		if(StringUtils.isEmpty(paramName)){
			paramName=parameter.getParameterName();
		}
		
		Object paramValue=webRequest.getParameter(paramName);
		if(null==paramValue){
			paramValue=decode.defaultValue();
		}
		if(decode.required()&&null==paramValue){
			throw new RuntimeException(paramName+"不能为空");
		}
		//解密操作
		
		//类型转换
		if(binderFactory!=null){
			WebDataBinder binder = binderFactory.createBinder(webRequest, null, paramName);
			paramValue = binder.convertIfNecessary(paramValue, parameter.getParameterType(), parameter);
		}
		return paramValue;
	}

}
